package com.cipe.cmrs.controllers;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cipe.cmrs.model.Cipeproject;
import com.cipe.cmrs.model.Keyword;
import com.cipe.cmrs.service.CipeprojectService;
import com.cipe.cmrs.service.CipeprojectstatusService;
import com.cipe.cmrs.service.CipeprojecttypeService;
import com.cipe.cmrs.service.CountryService;
import com.cipe.cmrs.service.DonorService;
import com.cipe.cmrs.service.DonorawardService;
import com.cipe.cmrs.service.KeywordService;
import com.cipe.cmrs.service.OrganizationtypeService;
import com.cipe.cmrs.service.PartnerService;
import com.cipe.cmrs.service.RegionService;
import com.cipe.cmrs.service.UserService;
import com.cipe.cmrs.service.UsertypeService;

@Controller
public class KnowledgeManagementController extends BaseController {

	private static final long serialVersionUID = 1815579886981166259L;
	@Autowired
	private CipeprojectService cipeprojectService;
	@Autowired
	private CountryService countryService;
	@Autowired
	private CipeprojecttypeService cipeprojecttypeService;
	@Autowired
	private RegionService regionService;
	@Autowired
	private CipeprojectstatusService cipeprojectstatusService;
	@Autowired
	private DonorawardService donorawardService;
	@Autowired
	private UserService userService;
	@Autowired
	private UsertypeService usertypeService;
	@Autowired
	private PartnerService partnerService;
	@Autowired
	private DonorService donorService;
	@Autowired
	private OrganizationtypeService organizationtypeService;
	@Autowired
	private KeywordService keywordService;

	private String findKnowledgeManagementView = "findKnowledgeManagement";

	@RequestMapping("/secure/findKnowledgeManagement.do")
    public String findKnowledgeManagement(@ModelAttribute("cipeproject") Cipeproject cipeproject,
        @RequestParam(value = "initiateSearch", required = false) String initiateSearch, Model model) {
        model.addAttribute("cipeproject", new Cipeproject());
        model.addAttribute("partnerList", partnerService.findAll());
        model.addAttribute("cipeprojecttypeList", cipeprojecttypeService.findAllOrderBy("displayName"));
        model.addAttribute("cipeprojectstatusList", cipeprojectstatusService.findAllOrderBy("displayName"));
        model.addAttribute("regionList", regionService.findAllOrderBy("displayName"));
        model.addAttribute("countryList", countryService.findAllOrderBy("displayName"));
        model.addAttribute("seniorProgramOfficerList", userService.findAllOrderBy("firstName"));
        model.addAttribute("programOfficerList", userService.findAllOrderBy("firstName"));
        model.addAttribute("programAssistantList", userService.findAllOrderBy("firstName"));
        model.addAttribute("keywordList", keywordService.findAllOrderBy("description"));
        model.addAttribute("organizationtypeList", organizationtypeService.findAllOrderBy("displayName"));
        model.addAttribute("themeList", cipeprojectService.getThemeList());
        if(StringUtils.isNotBlank(cipeproject.getThemColumn())) {
        	String fieldValuePair[] = cipeproject.getThemColumn().split(":");
        	
        	if (fieldValuePair[0].equals("themeaccesstoinfo")) {
        		cipeproject.setThemeaccesstoinfo(Integer.valueOf(fieldValuePair[1]));
        	}
        	if (fieldValuePair[0].equals("themebusassocdev")) {
        		cipeproject.setThemebusassocdev(Integer.valueOf(fieldValuePair[1]));
        	}
        	if (fieldValuePair[0].equals("themecorruption")) {
        		cipeproject.setThemecorruption(Integer.valueOf(fieldValuePair[1]));
        	}
        	if (fieldValuePair[0].equals("themedemocraticgovernance")) {
        		cipeproject.setThemedemocraticgovernance(Integer.valueOf(fieldValuePair[1]));
        	}
        	if (fieldValuePair[0].equals("themelegalregreform")) {
        		cipeproject.setThemelegalregreform(Integer.valueOf(fieldValuePair[1]));
        	}
        	if (fieldValuePair[0].equals("themewomenyouth")) {
        		cipeproject.setThemewomenyouth(Integer.valueOf(fieldValuePair[1]));
        	}
        	if (fieldValuePair[0].equals("themecorporategovernance")) {
        		cipeproject.setThemecorporategovernance(Integer.valueOf(fieldValuePair[1]));
        	}
        	if (fieldValuePair[0].equals("themeinformalsectorproperty")) {
        		cipeproject.setThemeinformalsectorproperty(Integer.valueOf(fieldValuePair[1]));
        	}
        	
        	
        }
        if (StringUtils.isNotBlank(initiateSearch)) {
            model.addAttribute("cipeprojectList", cipeprojectService.findKnowledgeManagement(cipeproject));
            model.addAttribute("cipeproject", cipeproject);
            model.addAttribute("initiateSearch", initiateSearch);
        }
        return findKnowledgeManagementView;
    }

	@RequestMapping("/secure/findSearchKnowledgeManagement.do")
    public String findSearchKnowledgeManagement(@ModelAttribute("cipeproject") Cipeproject cipeproject,
        @RequestParam(value = "initiateSearch", required = false) String initiateSearch, Model model) {
		 setThemValue(cipeproject);
		 model.addAttribute("cipeprojectList", cipeprojectService.findKnowledgeManagement(cipeproject));
		 return "searchResultKnowledgeManagement";
	}
	@RequestMapping("/secure/saveKnowledgeManagement.do")
	public String saveKnowledgeManagement(@ModelAttribute("cipeproject") Cipeproject cipeproject, BindingResult result, Model model, HttpServletRequest request) {
		String[] selectedKeywords = null;
		try {
			cipeproject = cipeprojectService.saveKnowledgeManagement(cipeproject, getUserId(request), false);
			saveMessage(request, getText("editKnowledgeManagement.message.success"));
			List<String> keywords = new ArrayList<String>();
			Collections.sort(cipeproject.getKeywords(), new Comparator<Keyword>() {
				public int compare(Keyword o1, Keyword o2) {
					if (o1.getDisplayName() != null && o2.getDisplayName() != null) {
						return o1.getDisplayName().compareTo(o2.getDisplayName());
					} else if (o1.getDisplayName() != null) {
						return 1;
					} else {
						return -1;
					}
				}
			});
			if (null != cipeproject.getKeywords()) {
				for (Keyword keyword : cipeproject.getKeywords()) {
					keywords.add(keyword.getId().toString());
				}
			}
			selectedKeywords = keywords.toArray(new String[keywords.size()]);
		} catch (Exception e) {
			logger.error(getText("error.transaction"), e);
			saveError(request, getText("error.transaction"));
		}
		cipeproject.setSelectedKeywords(selectedKeywords);
		model.addAttribute("cipeproject", cipeproject);
		model.addAttribute("partnerList", partnerService.findAll());
		model.addAttribute("donorawardList", donorawardService.findAll());
		model.addAttribute("cipeprojecttypeList", cipeprojecttypeService.findAll());
		model.addAttribute("cipeprojectstatusList", cipeprojectstatusService.findAll());
		model.addAttribute("regionList", regionService.findAll());
		model.addAttribute("countryList", countryService.findAll());
		model.addAttribute("seniorProgramOfficerList", userService.findAll());
		model.addAttribute("programOfficerList", userService.findAll());
		model.addAttribute("programAssistantList", userService.findAll());
		model.addAttribute("organizationtypeList", organizationtypeService.findAll());
		model.addAttribute("keywordList", cipeproject.getKeywords());
		return "editKnowledgeManagement";
	}

	@RequestMapping("/secure/showAddKnowledgeManagement.do")
	public String showAddKnowledgeManagement(Model model) {
		model.addAttribute("cipeproject", new Cipeproject());
		model.addAttribute("partnerList", partnerService.findAll());
		model.addAttribute("donorawardList", donorawardService.findAll());
		model.addAttribute("cipeprojecttypeList", cipeprojecttypeService.findAll());
		model.addAttribute("cipeprojectstatusList", cipeprojectstatusService.findAll());
		model.addAttribute("regionList", regionService.findAll());
		model.addAttribute("countryList", countryService.findAll());
		model.addAttribute("seniorProgramOfficerList", userService.findAll());
		model.addAttribute("programOfficerList", userService.findAll());
		model.addAttribute("programAssistantList", userService.findAll());
		model.addAttribute("organizationtypeList", organizationtypeService.findAll());
		model.addAttribute("keywordList", keywordService.findAll());
		return "editKnowledgeManagement";
	}

	@RequestMapping("/secure/showEditKnowledgeManagement.do")
	public String showEditKnowledgeManagement(@RequestParam Integer id, Model model) {
		Cipeproject cipeproject = cipeprojectService.findById(id);
		String[] selectedKeywords = null;
		List<String> keywords = new ArrayList<String>();
		if (null != cipeproject.getKeywords()) {
			for (Keyword keyword : cipeproject.getKeywords()) {
				keywords.add(keyword.getId().toString());
			}
		}
		selectedKeywords = keywords.toArray(new String[keywords.size()]);
		cipeproject.setSelectedKeywords(selectedKeywords);
		model.addAttribute("cipeproject", cipeproject);
		model.addAttribute("partnerList", partnerService.findAll());
		model.addAttribute("donorawardList", donorawardService.findAll());
		model.addAttribute("cipeprojecttypeList", cipeprojecttypeService.findAll());
		model.addAttribute("cipeprojectstatusList", cipeprojectstatusService.findAll());
		model.addAttribute("regionList", regionService.findAll());
		model.addAttribute("countryList", countryService.findAll());
		model.addAttribute("seniorProgramOfficerList", userService.findAll());
		model.addAttribute("programOfficerList", userService.findAll());
		model.addAttribute("programAssistantList", userService.findAll());
		// model.addAttribute("keywordList", keywordService.findAll());
		model.addAttribute("keywordList", cipeproject.getKeywords());
		model.addAttribute("organizationtypeList", organizationtypeService.findAll());
		return "editKnowledgeManagement";
	}

	@RequestMapping("/secure/showKnowledgeManagementList.do")
	public String showKnowledgeManagementList(Model model) {
		model.addAttribute("cipeprojects", cipeprojectService.findAll());
		return "knowledgeManagementList";
	}

	@RequestMapping("/secure/showViewKnowledgeManagement.do")
	public String showViewKnowledgeManagement(@RequestParam Integer id, Model model) {
		model.addAttribute("cipeproject", cipeprojectService.findById(id));
		model.addAttribute("partnerList", partnerService.findAll());
		model.addAttribute("donorawardList", donorawardService.findAll());
		model.addAttribute("cipeprojecttypeList", cipeprojecttypeService.findAll());
		model.addAttribute("cipeprojectstatusList", cipeprojectstatusService.findAll());
		model.addAttribute("regionList", regionService.findAll());
		model.addAttribute("countryList", countryService.findAll());
		model.addAttribute("seniorProgramOfficerList", userService.findAll());
		model.addAttribute("programOfficerList", userService.findAll());
		model.addAttribute("programAssistantList", userService.findAll());
		model.addAttribute("organizationtypeList", organizationtypeService.findAll());
		model.addAttribute("keywordList", keywordService.findAll());
		return "editKnowledgeManagement";
	}

	private void setThemValue(Cipeproject cipeproject) {
		String theme = cipeproject.getThemColumn();
		if (theme != null && !"".equals(theme)) {
			String[] str1 = theme.split("\\:");
			logger.debug(str1[0] + ": " + str1[1]);
			if ("themebusassocdev".equals(str1[0]))
				cipeproject.setThemebusassocdev(Integer.parseInt(str1[1]));
			if ("themelegalregreform".equals(str1[0]))
				cipeproject.setThemelegalregreform(Integer.parseInt(str1[1]));
			if ("themewomenyouth".equals(str1[0]))
				cipeproject.setThemewomenyouth(Integer.parseInt(str1[1]));
			if ("themeaccesstoinfo".equals(str1[0]))
				cipeproject.setThemeaccesstoinfo(Integer.parseInt(str1[1]));
			if ("themecorruption".equals(str1[0]))
				cipeproject.setThemecorruption(Integer.parseInt(str1[1]));
			if ("themecorporategovernance".equals(str1[0]))
				cipeproject.setThemecorporategovernance(Integer.parseInt(str1[1]));
			if ("themedemocraticgovernance".equals(str1[0]))
				cipeproject.setThemedemocraticgovernance(Integer.parseInt(str1[1]));
			
			if ("themeinformalsectorproperty".equals(str1[0]))
				cipeproject.setThemeinformalsectorproperty(Integer.parseInt(str1[1]));
			
		}
	}

	@RequestMapping(value = "/secure/loadKeywords.do", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, String> loadKeywordsViaAjax(@RequestParam Integer cipeprojectId, Model model) {
		SortedMap<String, String> temp = new TreeMap<String, String>();
		List<Keyword> keywords = keywordService.findAll();
		for (Keyword keyword : keywords) {
			temp.put(keyword.getDisplayName(), keyword.getId().toString());
		}
		Cipeproject cipeproject = cipeprojectService.findById(cipeprojectId);
		List<Keyword> savedKeywrods = cipeproject.getKeywords();
		for (Keyword keyword : savedKeywrods) {
			if (temp.containsValue(keyword.getId().toString())) {
				temp.remove(keyword.getDisplayName());
			}
		}
		Map<String, String> results = new LinkedHashMap<String, String>();
		Iterator<String> iterator = temp.keySet().iterator();
		while (iterator.hasNext()) {
			String key = iterator.next();
			results.put(temp.get(key), key);
		}
		return results;
	}
}
